package com.oracle.zebrafreelytraveling.ui;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.View;

import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.facebook.drawee.view.SimpleDraweeView;
import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResHotelList;
import com.oracle.zebrafreelytraveling.data.model.IntroBase;
import com.oracle.zebrafreelytraveling.net.HttpManager;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.CommonAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.MultiItemTypeAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.base.ViewHolder;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.wrapper.LoadMoreWrapper;
import com.oracle.zebrafreelytraveling.ui.fragment.IntroSlideDialogFragment;
import com.oracle.zebrafreelytraveling.utils.ClassInfoUtil;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;
import com.oracle.zebrafreelytraveling.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yydcnjjw on 2017/7/28.
 * 酒店分类activity
 */

public class ClassifyHotelActivity extends BaseActitvity {

    private static final String CITY_ID = "cityId";

    private RecyclerView mHotelRecycle;
    private CommonAdapter<ResHotelList.ResultBean> mHotelAdapter;
    private List<ResHotelList.ResultBean> mHotelList;
    private LoadMoreWrapper mLoadMoreWrapper;
    private SwipeRefreshLayout mHotelRefreshLayout;

    private ViewHolder mLoadMoreHolder;
    private int page = 1;
    private boolean isDataNull = false;
    private int cityId = 0;

    private Disposable mDisposable;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        getIntentData();
        initRecycle();
    }

    private void getIntentData(){
        Intent intent = getIntent();
        cityId = intent.getIntExtra(CITY_ID, -1);
    }

    private void initRecycle(){
        mHotelRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.hotel_refresh);
        mHotelRefreshLayout.setOnRefreshListener(() -> upDataHotelList(Constant.GET_DATA_TYPE_NOMAL));
        mHotelRecycle = (RecyclerView) findViewById(R.id.hotel_recycle_view);
        mHotelRecycle.setLayoutManager(new LinearLayoutManager(this));
        mHotelList = new ArrayList<>();

        mHotelAdapter = new CommonAdapter<ResHotelList.ResultBean>(this, R.layout.item_hotel, mHotelList) {
            @Override
            protected void convert(ViewHolder holder, ResHotelList.ResultBean resultBean, int position) {
                holder.setText(R.id.hotel_name, resultBean.getName());
                holder.setText(R.id.hotel_address, resultBean.getAddress());
//                LatLng from = new LatLng(mMapLocation.getLatitude(), mMapLocation.getLongitude());
                LatLng to = new LatLng(Double.parseDouble(resultBean.getLat()),
                        Double.parseDouble(resultBean.getLon()));
//                double distance = AMapUtils.calculateLineDistance(from, to);
                holder.setText(R.id.distance_location, "距离好远...");
                SimpleDraweeView draweeView = holder.getView(R.id.hotel_image);
                draweeView.setImageURI(resultBean.getLargePic());
            }
        };
        mHotelAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                IntroBase base = new IntroBase();
                base.setIntroName(mHotelList.get(position).getName());
                base.setIntroImage(mHotelList.get(position).getLargePic());
                base.setIntroContent(mHotelList.get(position).getIntro());
                base.setIntroLocation(mHotelList.get(position).getAddress());
                base.setIntroContact(mHotelList.get(position).getUrl());
                base.setLatitude(mHotelList.get(position).getLat());
                base.setLongitude(mHotelList.get(position).getLon());
                IntroSlideDialogFragment.newInstance(base, -1).showDialogFragment(getFragmentManager());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        mLoadMoreWrapper = new LoadMoreWrapper(mHotelAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.footer_loading);
        mLoadMoreWrapper.setOnLoadMoreListener(viewHolder -> {
            mLoadMoreHolder = viewHolder;
            if (!isDataNull){
                Log.d("isDataNull", "false");
                upDataHotelList(Constant.GET_DATA_TYPE_LOADMORE);
            } else {
                Log.d("isDataNull", "true");
                viewHolder.getConvertView().setVisibility(View.GONE);
            }
        });
        mHotelRecycle.setAdapter(mLoadMoreWrapper);
    }

    private void upDataHotelList(int type){
        if (cityId == 0){
            ToastUtil.showToast(getString(R.string.location_false));
            mHotelRefreshLayout.setRefreshing(false);
            mLoadMoreHolder.getConvertView().setVisibility(View.GONE);
            isDataNull = true;
            return;
        }
        HttpManager.getInstance().getService(Constant.VIEW_API)
                .getHotelList(cityId, page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResHotelList>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull ResHotelList resHotelList) {
                        ToastUtil.showToast(resHotelList.getReason());
                        if (resHotelList.getError_code() != Constant.API_SUCCESS){
                            isDataNull = true;
                            page = 0;
                            // TODO: 2017/8/11 模拟数据
                            mHotelList.addAll(ClassInfoUtil.getHotelList());
                            mLoadMoreWrapper.notifyDataSetChanged();
                            return;
                        }
                        if (type == Constant.GET_DATA_TYPE_LOADMORE){
                            mHotelList.addAll(resHotelList.getResult());
                        } else {
                            mHotelList.clear();
                            mHotelList.addAll(resHotelList.getResult());
                        }
                        isDataNull = false;
                        mLoadMoreWrapper.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("upDataHotelList", e.getMessage());
                        mHotelRefreshLayout.setRefreshing(false);
                        mLoadMoreHolder.getConvertView().setVisibility(View.GONE);
                    }

                    @Override
                    public void onComplete() {
                        mHotelRefreshLayout.setRefreshing(false);
                        mLoadMoreHolder.getConvertView().setVisibility(View.GONE);
                    }
                });
        page++;
    }

    public static void startHotelActivity(Activity activity, int cityId){
        Intent intent = new Intent(activity, ClassifyHotelActivity.class);
        intent.putExtra(CITY_ID, cityId);
        activity.startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清除 Disposable
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        page = 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_hotel_classify;
    }
}
